package com.vng.zini.gifapp.components;

import java.io.IOException;

import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.util.Log;

import com.vng.zini.gifapp.config.AppConstant;
import com.vng.zini.gifapp.config.AppParameters;

public class GIFCamera {
	public static Camera getCameraInstance() {
		Camera c = null;
		
		try {
			if (AppParameters.numberCam == 0) {

			} else if (AppParameters.numberCam == 1) {
				c = Camera.open(0);
			} else {
				if (AppParameters.cameraID == 1) {
					c = Camera.open();
				} else {
					Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
					for (int camIdx = 0; camIdx < AppParameters.numberCam; camIdx++) {
						Camera.getCameraInfo(camIdx, cameraInfo);
						if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
							try {
								c = Camera.open(camIdx);
							} catch (RuntimeException e) {
								Log.e("USER_TAG",
										"Camera failed to open: "
												+ e.getLocalizedMessage());
							}
						}

					}
				}

			}

		} catch (Exception e) {
			// Camera is not available (in use or does not exist)
			System.out.println(e.getMessage());
			e.printStackTrace();
		}
		if(c!=null){
			if(!AppParameters.isLightOn){
				Parameters p = c.getParameters();
                p.setFlashMode(Parameters.FLASH_MODE_OFF);
                c.setParameters(p);
			}
			else{
				Parameters p = c.getParameters();
                p.setFlashMode(Parameters.FLASH_MODE_TORCH);
                c.setParameters(p);
			}
		}
		return c; // returns null if camera is unavailable
	}
	
	public static Camera.Size getBestSize(){
		if(AppParameters.listSize == null){
			return null;
		}
		Camera.Size bestSize = null;
		for(int i=0;i<AppParameters.listSize.size();i++){
			Camera.Size  size = AppParameters.listSize.get(i);
			if(size.height >= AppConstant.CAMERA_STANDARD_HEIGHT && size.width >= AppConstant.CAMERA_STANDARD_WIDTH){
				bestSize = size;
			}
			else{
				break;
			}
		}
		
		return bestSize;
	}
}
